// 二维数组相加
a1 = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
console.log(a1.reduce((a, b) => {
    return a.concat(b)
}).reduce((a, b) => {
    return a + b
}));

// 打印矩阵
function printMatrx(n, m) {
    for (i = 1; i <= n; i++) {
        str = "";
        for (j = 1; j <= m; j++) {
            str += "*";
        }
        console.log(str);
    }
}

printMatrx(3, 3);


// 打印乘法表
function printMultiplication() {
    for (var i = 1; i <= 9; i++) {
        str = "";
        for (var j = 1; j <= i; j++) {
            temp = j + "*" + i + "=" + i * j;
            str += temp + "\t";
        }
        console.log(str);
    }
}

printMultiplication();


// 打印费氏级数
function printFibonacci(n) {
    var fibonacci = [0, 1, 1];
    for (var i = 2; i <= n; i++) {
        fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
    }
    console.log(n + "的费氏级数为:" + fibonacci[n]);
}

printFibonacci(30);



// 二分查找
var array = [123, 456, 789, 1234, 45643];

function binarySearch(array, l, r, key) {
    if (l > r) return -1;
    var mid = parseInt((l + r) / 2);
    if (array[mid] == key) {
        return mid;
    } else {
        if (array[mid] > key) {
            return binarySearch(array, l, mid - 1, key);
        } else {
            return binarySearch(array, mid + 1, r, key);
        }
    }
}

console.log(binarySearch(array, 0, array.length, 8888));


//冒泡
var arrayM = [8, 52, 12, 421, 32]

function sortM(array) {
    for (var i = 0; i < array.length; i++) {
        for (var j = 0; j < array.length - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                temp = array[j + 1];
                array[j + 1] = array[j];
                array[j] = temp;
            }
        }
    }
    console.log(array);
}

sortM(arrayM)

//选择
function sortSelect(array) {
    var minIndex = -1;
    for (var i = 0; i < array.length - 1; i++) {
        minIndex = i;
        for (var j = i + 1; j < array.length; j++) {
            if (array[j] < array[minIndex]) {
                minIndex = j;
            }
        }
        temp = array[i];
        array[i] = array[minIndex];
        array[minIndex] = temp;
    }
    console.log(array);
}

sortSelect(arrayM)